package com.rest.observer;

import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.gson.JsonSyntaxException;
import com.rest.exception.ApiException;

import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import retrofit2.HttpException;

/**
 * @Description: java类作用描述
 * @Author: lzp
 * @CreateDate: 2022/2/28 15:46
 * @UpdateRemark: 更新说明
 */
public abstract class BaseObserver<T> implements Observer<T> {
    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onNext(@NonNull T t) {
        onSuccess(t);
    }

    @Override
    public void onError(@NonNull Throwable e) {
        String errorMsg = "未知错误";
        if (e instanceof UnknownHostException) {
            errorMsg = "网络不可用";
        } else if (e instanceof SocketTimeoutException) {
            errorMsg = "请求网络超时";
        } else if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            errorMsg = convertStatusCode(httpException);
        } else if (e instanceof ParseException || e instanceof JSONException || e instanceof JsonSyntaxException) {
            errorMsg = "数据解析错误";
        } else if (e instanceof ApiException) {
            errorMsg = ((ApiException) e).errorMessage;
        }
        LogUtil.e(errorMsg);
    }

    private static String convertStatusCode(HttpException httpException) {
        String msg;
        if (httpException.code() >= 500 && httpException.code() < 600) {
            msg = "服务器处理请求出错";
        } else if (httpException.code() >= 400 && httpException.code() < 500) {
            msg = "服务器无法处理请求";
        } else if (httpException.code() >= 300 && httpException.code() < 400) {
            msg = "请求被重定向到其他页面";
        } else {
            msg = httpException.message();
        }
        return msg;
    }

    @Override
    public void onComplete() {

    }

    public abstract void onSuccess(T result);
}